package com.atguigu.msmservice.controller;

import com.atguigu.commonutils.R;
import com.atguigu.commonutils.RandomUtil;
import com.atguigu.msmservice.service.MsmService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;
@Api(description = "发送短信")
@RestController
@CrossOrigin
@RequestMapping("/edumsm/msm")
public class MsmApiController {

    @Autowired
    MsmService msmService;

    //注入操作Redis的模板
    @Autowired
    RedisTemplate<String,String> redisTemplate;
    //发送短信的方法
    @ApiOperation("发送短信的方法")
    @GetMapping("send/{phone}")
    public R sendMsm( @PathVariable("phone") String phone) {
        //1、从redis中获取验证码，如果获取到直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)){ return R.ok(); }
       //2、如果redis获取不到，进行阿里云发送
        // 3、生成随机数，传递阿里云进行发送
        String fourBitRandom = RandomUtil.getFourBitRandom();
        HashMap<String, String> parammap = new HashMap<>();
        parammap.put("code",fourBitRandom);
       Boolean isSend =  msmService.send(phone,parammap);

        if (isSend){
            //阿里云发送成功，把发送成功的验证码放入redis缓存中并设置5分钟保存的时间，不可能一直有效
            redisTemplate.opsForValue().set(phone,fourBitRandom,5, TimeUnit.MINUTES);
            return  R.ok();
        }else {
            return R.error().message("发送短信失败！");
        }

    }

}
